//
//  UIViewController+App.m
//  ZZmetro
//
//  Created by 一介布衣 on 2020/6/5.
//  Copyright © 2020 一介布衣. All rights reserved.
//

#import "UIViewController+App.h"
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
#import "AppLoadingView.h"
#import <IBase/Constants.h>
#import "AppDelegate+App.h"

#define ENUM_TO_CaseValue(enumValue) (@#enumValue)//枚举转字符串


@implementation UIViewController (App)
static NSString *backIcon = NULL;

#pragma mark -

static void swizzIt(Class class, SEL originalSelector, SEL swizzledSelector)
{
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    BOOL didAddMethod =
    class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    
    if (didAddMethod)
    {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));
    } else
    {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

+ (void)load
{
    swizzIt([self class], @selector(baseViewDidLoad), @selector(viewDidLoad));
    swizzIt([self class], @selector(baseViewWillAppear:), @selector(viewWillAppear:));
    swizzIt([self class], @selector(baseViewWillDisappear:), @selector(viewWillDisappear:));
}

- (void)baseViewWillDisappear:(BOOL)animated
{
    NSString *str = [NSString stringWithFormat:@"%@", self.class];
    if (![str containsString:@"UI"])
    {
        self.navigationController.interactivePopGestureRecognizer.delegate = NULL;
    }
    [self baseViewWillDisappear:animated];
}

- (void)baseViewWillAppear:(BOOL)animated
{
    NSString *str = [NSString stringWithFormat:@"%@", self.class];
    if (![str containsString:@"UI"])
    {
        ((AppDelegate *)([UIApplication sharedApplication].delegate)).currentCtl = self;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    [self baseViewWillAppear:animated];
}

- (void)baseViewDidLoad
{
    NSString *str = [NSString stringWithFormat:@"%@", self.class];
    if (![str containsString:@"UI"])
    {
        self.view.backgroundColor = HEXCOLOR(0xeeeeee);
    }
    [self baseViewDidLoad];
}

#pragma mark -
+ (void)setNavigationBarWithStyle:(NAV_BAR_STYLE)style
{
    switch (style)
    {
        case NAV_BAR_STYLE_1:
        {
            backIcon = @"back1";
            
            UIColor *color1 = HEXCOLOR(0x333333);
            UIColor *color2 = HEXCOLOR(0xe2e2e2);
            UIColor *color3 = HEXCOLOR(0XF3F6F7);
            
            UINavigationBar *bar = [UINavigationBar appearance];
            
            UIImage *image = [UIImage imageNamed:backIcon];
            bar.backIndicatorImage = image;
            bar.backIndicatorTransitionMaskImage = image;
            bar.tintColor = color1;
            bar.barTintColor = [UIColor whiteColor];
            bar.titleTextAttributes = @{NSForegroundColorAttributeName: color1};
            
            UIBarButtonItem *item = [UIBarButtonItem appearance];
            [item setBackButtonTitlePositionAdjustment:UIOffsetMake(-500, 0) forBarMetrics:UIBarMetricsDefault];
            item.tintColor = color1;
            [item setTitleTextAttributes:@{NSForegroundColorAttributeName:color1,NSFontAttributeName:[UIFont  systemFontOfSize:15]} forState:UIControlStateNormal|UIControlStateHighlighted|UIControlStateSelected|UIControlStateFocused|UIControlStateReserved|UIControlStateDisabled];
            
            [UITableView appearance].separatorColor = color2;
            [UITableViewHeaderFooterView appearance].contentView.backgroundColor = color3;
        }
            break;
        case NAV_BAR_STYLE_2:
        {
            backIcon = @"back2";
            
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
            
            UIColor *color2 = HEXCOLOR(0x5A7EEE);
            
            UINavigationBar *bar = [UINavigationBar appearance];
            
            UIImage *image = [UIImage imageNamed:backIcon];
            bar.backIndicatorImage = image;
            bar.backIndicatorTransitionMaskImage = image;
            bar.translucent = NO;
            bar.barTintColor = color2;
            bar.tintColor = [UIColor whiteColor];
            [bar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
            
        }
            break;
        case NAV_BAR_STYLE_3:
        {
            backIcon = @"back3";
            
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
            
            UIColor *color1 = HEXCOLOR(0xeeeeee);
            UIColor *color2 = HEXCOLOR(0x1d1d20);
            
            UINavigationBar *bar = [UINavigationBar appearance];
            
            UIImage *image = [UIImage imageNamed:backIcon];
            bar.backIndicatorImage = image;
            bar.backIndicatorTransitionMaskImage = image;
            bar.translucent = NO;
            bar.barTintColor = color1;
            bar.tintColor = [UIColor whiteColor];
            [bar setTitleTextAttributes:@{NSForegroundColorAttributeName : color2}];
        }
            break;
        default:
        {
            backIcon = NULL;
        }
            break;
    }
}

#pragma mark -
- (void)initWithBackButton
{
    if (backIcon)
    {
        [self initWithBackButton:backIcon];
    }
}

- (void)initWithBackButton:(NSString *)iconName
{
    if ([self.navigationController.viewControllers count] > 0)
    {
        [self mandatoryWithBackButton:iconName];
    }
}

- (void)mandatoryWithBackButton:(NSString *)iconName
{
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setFrame:CGRectMake(0, 0, 44, 44)];
    back.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [back setImage:[UIImage imageNamed:iconName] forState:UIControlStateNormal];
    
    [back addTarget:self action:@selector(popController) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = barButton;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}

- (void)initWithRightButton:(NSString *)name buttonWidth:(CGFloat)buttonWidth selector:(SEL)selector
{
    if (name == nil || buttonWidth == 0)
    {
        self.navigationItem.rightBarButtonItem = nil;
        
        return;
    }
    
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    [right setFrame:CGRectMake(0, 0, buttonWidth, 44)];
    [right setTitle:name forState:UIControlStateNormal];
    right.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    
    [right addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:right];
    self.navigationItem.rightBarButtonItem = barButton;
}

- (void)popController
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    if ([array count] > 0)
    {
        for (int i = 0;i < [array count];i ++)
        {
            UIViewController *viewController = [array objectAtIndex:i];
            if ([viewController isEqual:self])
            {
                if (i == [array count] - 1)
                {
                    [self.navigationController popViewControllerAnimated:YES];
                } else
                {
                    [array removeObjectAtIndex:i];
                    self.navigationController.viewControllers = array;
                }
                break;
            }
        }
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if(self.navigationController.viewControllers.count == 1)
    {
        return NO;
    } else
    {
        return YES;
    }
}

- (void)addExceptionViewWithSelector:(SEL)selector state:(VIEW_DATA_LOAD_STATE)state
{
    [self addExceptionViewWithSelector:selector state:state tipString:NULL];
}

- (void)addExceptionViewWithSelector:(SEL)selector state:(VIEW_DATA_LOAD_STATE)state tipString:(NSString *)tipString
{
    NSInteger tag = 9999;
    AppLoadingView *loadView = (AppLoadingView *)[self.view viewWithTag:tag];
    
    if (loadView && [loadView isKindOfClass:[AppLoadingView class]])
    {
        [loadView removeFromSuperview];
        loadView = nil;
    }
    
    if (state == VIEW_DATA_LOAD_STATE_NONE)
    {
        return;
    }
    
    loadView = [AppLoadingView createWithView];
    loadView.tag = tag;
    loadView.frame = self.view.bounds;
    loadView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    if (state == VIEW_DATA_LOAD_STATE_FAILED)
    {
        loadView.isFailedState = YES;
    } else
    {
        loadView.isFailedState = NO;
    }
    [loadView addReLoadActionWithTarget:self action:selector];
    if (tipString)
    {
        loadView.tipString = tipString;
    } else
    {
        switch (state)
        {
            case VIEW_DATA_LOAD_STATE_LOADING:
            {
                loadView.tipString = @"正在加载数据";
            }
                break;
            case VIEW_DATA_LOAD_STATE_SUCCESS:
            {
                loadView.tipString = @"加载成功";
            }
                break;
            case VIEW_DATA_LOAD_STATE_FAILED:
            {
                loadView.tipString = @"页面请求失败，请稍后再试";
            }
                break;
            case VIEW_DATA_LOAD_STATE_NODATA:
            {
                loadView.tipString = @"暂无数据";
            }
                break;
            default:
            {
                loadView.tipString = @"";
            }
                break;
        }
    }
    [self.view addSubview:loadView];
    
    [self.view sendSubviewToBack:loadView];
}

- (void)closeCurrentViewController
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    
    for (UIViewController *viewController in array)
    {
        if ([viewController isEqual:self])
        {
            [array removeObject:viewController];
            
            break;
        }
    }
    
    self.navigationController.viewControllers = array;
}

- (UIViewController *)topViewController
{
    UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (true)
    {
        if ([controller isKindOfClass: [UINavigationController class]])
        {
            UINavigationController* nav = (UINavigationController*)controller;
            controller = nav.visibleViewController;
        } else if ([controller isKindOfClass:[UITabBarController class]])
        {
            UITabBarController *tabBarCtl = (UITabBarController*)controller;
            if (tabBarCtl.selectedViewController)
            {
                controller = tabBarCtl.selectedViewController;
            }
        } else if (controller.presentedViewController)
        {
            controller = controller.presentedViewController;
        } else
        {
            break;
        }
    }
    
    return controller;
}

@end
